﻿using Consul;

namespace ProductService
{
    public static class ConsulBuilderExtensions
    {
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime = null)
        {
            var ip = configuration["Consul:Ip"];
            var port = configuration["Consul:port"];


            string serviceIp = "";
            int servicePort = 0;
            //从配置文件获取
            if (!string.IsNullOrEmpty(configuration["ListenSetting:Ip"]) && !string.IsNullOrEmpty(configuration["ListenSetting:Port"]))
            {
                serviceIp = configuration["ListenSetting:Ip"];
                servicePort = int.Parse(configuration["ListenSetting:Port"]);
            }
            else
            {
                // 从命令行 参数获取  dotnet run --ip=127.0.0.1 --port=1234
                serviceIp = configuration["ip"];
                servicePort = int.Parse(configuration["port"]);
              
            }
            Console.WriteLine($"api server ip :{serviceIp} ,port:{servicePort}");

            //请求注册的 Consul 地址
            var consulClient = new ConsulClient(
                config =>
                {
                    config.Address = new Uri($"http://{ip}:{port}");//consul的地址
                    config.Datacenter = "dc1";
                }
                );

            var serviceId = "productService-" + Guid.NewGuid();
            AgentServiceRegistration registration = new AgentServiceRegistration();
            registration.Address = serviceIp;
            registration.Port = servicePort;
            registration.Name = "productService";
            registration.ID = serviceId;

            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                HTTP = $"http://{serviceIp}:{servicePort}/api/health/check",//健康检查地址
                Timeout = TimeSpan.FromSeconds(30)
            };
            registration.Check = httpCheck;

            var result = consulClient.Agent.ServiceRegister(registration).Result;
            if (lifetime != null)
            {
                lifetime.ApplicationStopped.Register(() => {
                    Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {serviceId} is stoped!!");
                    consulClient.Agent.ServiceDeregister(serviceId).Wait();
                });
            }

            return app;
        }
    }

}
